<?php
//首页动态内容的函数

function getIndexUserInfo()
{
	return tplFetch('inc/index/user_info');
}

/**
 * 热门杂志列表
 */
function getIndexShops(){
	global $_FANWE;
	$args = array();
	$cache_file = getTplCache('inc/index/shop',array(),1);
	if(getCacheIsUpdate($cache_file,SHARE_CACHE_TIME,1))
	{
		$args['shop_list'] = FDB::fetchAll('SELECT * FROM '.FDB::table('shop').' WHERE shop_logo > 0 ORDER BY sort ASC, shop_id asc limit 0,30');
	}
	return tplFetch('inc/index/shop',$args,'',$cache_file);
}

/**
 * 首页分类推荐分享
 */
function getIndexCateShare()
{
 	global $_FANWE;
 	$args = array();
 	FanweService::instance()->cache->loadCache('goods_category');
 	$index_cids = $_FANWE['cache']['goods_category']['index'];
 	foreach($index_cids as $k => $cid) {
 	    $cateinfo = $_FANWE['cache']['goods_category']['all'][$cid];
 	    if($cateinfo['parent_id'] != 0) {
 	        unset($index_cids[$k]);
 	    }
 	}
	$cate_list = array();
	if(count($index_cids) > 0)
	{
		foreach($index_cids as $cid)
		{
			$cate_list[$cid] = false;
		}

		$indexData = cache_read('index');
		$timer = cache_read('index_timer');
		if(!$timer || $timer['expire'] < time()) {
		    $index = $timer ? ($timer['index'] + 1) : 0;
		    cache_write('index_timer', array('index' => $index, 'expire' => time()+3600));
		} else {
		    $index = $timer['index'];
		}

		foreach($cate_list as $cid => $cate) {
		    $cateinfo = $_FANWE['cache']['goods_category']['all'][$cid];
			$cate_list[$cid]['cate'] = $cateinfo;
			foreach($indexData[$cid] as $pos => $links) {
			    $cate_list[$cid]['data'][$pos] = $links[$index % count($links)];
			}
			foreach($cate_list[$cid]['cate']['childs'] as $v) {
			    $v1 = $_FANWE['cache']['goods_category']['all'][$v];
			    if($v1['is_index'] == '1') {
			        $cate_list[$cid]['children'][$v] = $v1;
			    }
			}
		}

		$args['cate_list'] = $cate_list;
	}

	return tplFetch('inc/index/index_cate_share',$args);
}

function cache_write($name, $value, $expire = 0) {
    if(is_array($value)) {
        $value = var_export($value, true);    
    }
    
    $filename = FANWE_ROOT . '/public/' . $name . '.php';
    $data = '<?php'."\n";
    if($expire > 0) {
        $data .= 'if(time()>' . (time() + $expire) . ')return false;' . "\n";
    }
    $data .= 'return ' . $value . ';'."\n".'?>';
    file_put_contents($filename, $data);
    chmod($filename, 0777);
}

function cache_read($name) {
    $filename = FANWE_ROOT . '/public/' . $name . '.php';
    
    if(!file_exists($filename)) {
        return false;    
    }
    
    return include $filename;
}
